import React, { Component } from 'react';
import { Table } from 'antd';

import styles from './index.less';

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

class SimpleTable extends Component {
  handleTableChange = (pagination, filtersArg, sorter) => {
    const { onChange } = this.props;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    onChange(params);
  };

  render() {
    const { data, rowKey, ...rest } = this.props;
    const { list = [], total = 0, pageNo = 1, pageSize = 10 } = data || {};

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      // position: 'both',
      showTotal: nums => `共 ${nums} 条`,
      total,
      pageSize,
      current: pageNo,
    };

    return (
      <div className={styles.simpleTable}>
        <Table
          {...rest}
          size="small"
          rowKey={rowKey || 'id'}
          dataSource={list}
          pagination={paginationProps}
          onChange={this.handleTableChange}
        />
      </div>
    );
  }
}

export default SimpleTable;
